package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReqortServiceImpl implements ReportService {

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private WorkspaceService workspaceService;

	/**
	 * 统计指定时间区域内的营业额
	 * @param begin
	 * @param end
	 * @return
	 */
	@Override
	public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
		//统计订单时间在begin到end之间，订单状态为已完成的实收金额集合，并以逗号隔开
		//创建一个集合存放begin到end的日期集合
		List<LocalDate> dateList=new ArrayList<>();
		dateList.add(begin);
		//构建begin到end的集合
		while (!begin.equals(end)) {
			begin = begin.plusDays(1);
			dateList.add(begin);
		}


		//存放每天营业额集合
		List<Double> turnoverList=new ArrayList<>();
		//查询订单时间在begin到end之间的订单
		for (LocalDate date : dateList) {
			//把LocalDate对象转为LocalDateTime对象
			LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
			LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

			//数据封装
			Map map=new HashMap();
			map.put("begin",beginTime);
			map.put("end",endTime);
			map.put("status", Orders.COMPLETED);
			//执行sql语句：select sum(amount) from orders where order_time>beginTime and order_time<endTime and status=5
			Double turnover=orderMapper.sumByMap(map);
			//如果当天没有营业额，则把null改为0;
			turnover=turnover==null?0:turnover;
			//添加营业额到集合中
			turnoverList.add(turnover);
		}

		return TurnoverReportVO.builder()
				.dateList(StringUtils.join(dateList, ","))
				.turnoverList(StringUtils.join(turnoverList,","))
				.build();
	}

	/**
	 * 统计每天用户总量和每天新增用户量
	 * @param begin
	 * @param end
	 * @return
	 */
	@Override
	public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
		//创建集合用于存储begin到end每天的日期
		List<LocalDate> dateList=new ArrayList<>();
		dateList.add(begin);
		while (!begin.equals(end)) {
			begin = begin.plusDays(1);
			dateList.add(begin);
		}
		//创建集合存放每天的用户总量
		List<Integer> totalUserList=new ArrayList<>();
		//创建集合存放每天新增的用户量
		List<Integer> newUserList =new ArrayList<>();
		//计算当天的用户总量
		for (LocalDate date : dateList) {
			//创建当天的开始时间到结束时间
			LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
			LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
			//当天用户总量是用户创建时间小于endTime的用户总量
			Map map=new HashMap();
			map.put("end",endTime);
			//select count(id) from user where create_time<end
			Integer userNumber=	userMapper.countByMap(map);
			//如果为null,就改为0
			userNumber=userNumber==null?0:userNumber;
			totalUserList.add(userNumber);

			//当天新增用户量是创建时间大于beginTime,小于endTime的用户数量
			map.put("begin",beginTime);
			//select count(id) from user where create_time<end and create_time>begin
			Integer adduserNumber= userMapper.countByMap(map);
			//如果为null,就改为0
			userNumber=userNumber==null?0:userNumber;
			newUserList.add(adduserNumber);
		}

		return UserReportVO.builder()
				.dateList(StringUtils.join(dateList,","))
				.totalUserList(StringUtils.join(totalUserList,","))
				.newUserList(StringUtils.join(newUserList,","))
				.build();
	}

	/**
	 * 订单统计
	 * @param begin
	 * @param end
	 * @return
	 */
	@Override
	public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
		//创建集合存储日期
		List<LocalDate> dateList=new ArrayList<>();
		dateList.add(begin);
		while (!begin.equals(end)) {
			begin = begin.plusDays(1);
			dateList.add(begin);
		}
		//创建集合存储每日订单总数
		List<Integer> orderCountList=new ArrayList<>();
		//创建集合存储每日有效订单总数
		List<Integer> validOrderCountList=new ArrayList<>();
		for (LocalDate date :dateList){
			LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
			LocalDateTime endTime =LocalDateTime.of(date,LocalTime.MAX);
			//select count(id) from orders where order_time>beginTime and order_time<endTime
			Map map=new HashMap();
			map.put("begin",beginTime);
			map.put("end",endTime);
			Integer orderCount=	orderMapper.countByMap(map);
			//插入集合中
			orderCountList.add(orderCount);

			//查询有效订单量
			map.put("status",Orders.COMPLETED);
			Integer validOrderCount=orderMapper.countByMap(map);
			validOrderCountList.add(validOrderCount);
		}
		//时间区间内的订单总数
		Integer totalOrderCount=orderCountList.stream().reduce(Integer::sum).get();
		//时间区间内的有效订单总数
		Integer ValidOrderCount =validOrderCountList.stream().reduce(Integer::sum).get();
		//订单完成率
		Double orderCompletionRate=0.0;
		if(ValidOrderCount !=0) {
			//转换为double类型
			orderCompletionRate = ValidOrderCount.doubleValue()/ totalOrderCount.doubleValue();
		}
		return OrderReportVO.builder()
				.dateList(StringUtils.join(dateList,","))
				.orderCountList(StringUtils.join(orderCountList,","))
				.validOrderCountList(StringUtils.join(validOrderCountList,","))
				.validOrderCount(ValidOrderCount)
				.totalOrderCount(totalOrderCount)
				.orderCompletionRate(orderCompletionRate)
				.build();
	}

	/**
	 * 商品销量top10
	 * @param begin
	 * @param end
	 * @return
	 */
	@Override
	public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
		//要求：时间区间内，商品名称按商品销量递减,
		//sql语句：select od.name ,sum (od.number) from order o,order_detail od where od.order_id=id and status=5 and 时间区间内
		//group by od.name order by desc limit 0,10
		//转为LocalDateTime对象
		LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);
		LocalDateTime endTime =LocalDateTime.of(end,LocalTime.MAX);
		//查询
		List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
		//使用流对象封装集合
		List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
		List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
		return SalesTop10ReportVO.builder()
				.nameList(StringUtils.join(nameList,","))
				.numberList(StringUtils.join(numberList,","))
				.build();
	}

	/**
	 * 导出运营数据报表
	 * @param response
	 */
	@Override
	public void exportBusinessData(HttpServletResponse response) {
		//查询数据库获得运营数据...查询近30天
		//30天前
		LocalDate dateBegin=LocalDate.now().minusDays(30);
		//昨天
		LocalDate dateEnd=LocalDate.now().minusDays(1);
		//获取运营数据
		BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

		//通过poi将数据写入Excel模板
		InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
		try {
			XSSFWorkbook excel=new XSSFWorkbook(in);
			//获取页对象
			XSSFSheet sheet1=excel.getSheet("sheet1");
			//获取行对象
			//第2行
			XSSFRow row=sheet1.getRow(1);
			//填充数据--时间
			row.getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);
			//填充数据--概览数据
			//第4行
			row=sheet1.getRow(3);
			row.getCell(2).setCellValue(businessData.getTurnover());
			row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
			row.getCell(6).setCellValue(businessData.getNewUsers());
			//第5行
			row=sheet1.getRow(4);
			row.getCell(2).setCellValue(businessData.getValidOrderCount());
			row.getCell(4).setCellValue(businessData.getUnitPrice());

			//填充明细数据
			//遍历每一天
			for (int i = 0; i < 30; i++) {
				LocalDate date=dateBegin.plusDays(i);
				BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
				//行数
				row=sheet1.getRow(i+7);
				row.getCell(1).setCellValue(date.toString());
				row.getCell(2).setCellValue(businessDataVO.getTurnover());
				row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
				row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
				row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
				row.getCell(6).setCellValue(businessDataVO.getNewUsers());
			}

			//通过输出流将Excel文件下载到客户端游览器
			ServletOutputStream out = response.getOutputStream();
			excel.write(out);

			//关闭资源
			out.close();
			excel.close();

		} catch (Exception e) {
			e.printStackTrace();
		}





	}
}
